﻿using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

namespace Hont.AStar
{
    public class HontAStarUnityEditorHelper
    {
        const int CLEAR_HIER_DATA_MAGIC_NUMBER = 30;

        public static Bounds BuildBounds(Vector3[] points)
        {
            var xMin = points.Min(m => m.x);
            var yMin = points.Min(m => m.y);
            var zMin = points.Min(m => m.z);
            var xMax = points.Max(m => m.x);
            var yMax = points.Max(m => m.y);
            var zMax = points.Max(m => m.z);

            var min = new Vector3(xMin, yMin, zMin);
            var max = new Vector3(xMax, yMax, zMax);

            return new Bounds() { min = min, max = max };
        }

        public static Bounds CombineBounds(Bounds[] boundsArr)
        {
            if (boundsArr.Length == 0) return default(Bounds);
            if (boundsArr.Length == 1) return boundsArr[0];

            var points = boundsArr.SelectMany(m => new Vector3[] { m.min, m.max });
            return BuildBounds(points.ToArray());
        }

        public static HontAStarUnityDebugNode[] GetChildDebugNodes(HontAStarUnity root)
        {
            var childList = new List<HontAStarUnityDebugNode>();
            foreach (Transform item in root.transform)
            {
                var node = item.GetComponent<HontAStarUnityDebugNode>();
                if (node == null) continue;

                childList.Add(node);
            }

            return childList.ToArray();
        }

        public static void ClearHierData(Transform root)
        {
            for (int i = 0; i < CLEAR_HIER_DATA_MAGIC_NUMBER; i++)
            {
                foreach (Transform item in root.transform)
                {
                    UnityEngine.Object.DestroyImmediate(item.gameObject);
                }
            }
        }
    }
}
